package com.hoperun.checkcloth.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.content.res.ResourcesCompat
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.RecyclerView
import com.hoperun.checkcloth.R
import com.hoperun.checkcloth.databinding.ItemStuffCheckInfoBinding
import com.hoperun.checkcloth.entity.MaterialEntity

class StuffCheckInfoAdapter : RecyclerView.Adapter<StuffCheckInfoVm>() {
    private val dataSet = mutableListOf<MaterialEntity>()
    var itemSelected: ((MaterialEntity?) -> Unit)? = null

    public fun setDataSet(list: List<MaterialEntity>) {
        dataSet.apply {
            clear()
            addAll(list)
        }
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): StuffCheckInfoVm {
        val binding: ItemStuffCheckInfoBinding = DataBindingUtil.inflate(LayoutInflater.from(parent.context), R.layout.item_stuff_check_info, parent, false)
        return StuffCheckInfoVm(binding)
    }

    override fun onBindViewHolder(holder: StuffCheckInfoVm, position: Int) {
        holder.binding.text = dataSet[position].szqc
        holder.binding.checked = dataSet[position].isSelect

        holder.binding.root.setOnClickListener {
            dataSet.forEach { item -> item.isSelect = false }
            dataSet[position].isSelect = true
            itemSelected?.invoke(dataSet[position].takeIf { it.isSelect })
            notifyDataSetChanged()
        }

        val bgColor = if (dataSet[position].checked == "1") R.color.tran_black else R.color.transparent
        holder.binding.root.apply {
            setBackgroundColor(ResourcesCompat.getColor(resources, bgColor, null))
        }
    }

    override fun getItemCount(): Int = dataSet.size

}

class StuffCheckInfoVm(val binding: ItemStuffCheckInfoBinding) : RecyclerView.ViewHolder(binding.root)

